import router from './router'
import store from './store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { isRelogin } from '@/http/request'
import { getToken } from '@/utils/token'
import { Loading } from 'element-ui'
// 访问加载效果
let serverLoadingInstance = null
NProgress.configure({ showSpinner: true })

// 增加三方登陆
const whiteList = [
    '/login',
    '/social-login',
    '/auth-redirect',
    '/bind',
    '/register',
    '/oauthLogin/gitee',
    '/404'
]

router.beforeEach((to, from, next) => {
    serverLoadingInstance = Loading.service({
        background: 'rgba(134,134,134, 1)',
        customClass: 'server-loading'
    })
    NProgress.start()
    if (getToken()) {
        /* has token*/
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done()
            serverLoadingInstance && serverLoadingInstance.close()
        } else {
            if (store.getters.roles.length === 0) {
                isRelogin.show = true
                // 判断当前用户是否已拉取完 user_info 信息
                store
                    .dispatch('GetInfo')
                    .then(() => {
                        // 获取字典数据
                        store.dispatch('dict/loadDictDatas')
                        isRelogin.show = false
                        store.dispatch('GenerateRoutes').then(accessRoutes => {
                            // 根据 roles 权限生成可访问的路由表
                            // 动态添加可访问路由表
                            for (
                                let index = 0;
                                index < accessRoutes.length;
                                index++
                            ) {
                                router.addRoute(accessRoutes[index])
                            }
                            // hack方法 确保addRoutes已完成
                            next({ ...to, replace: true })
                        })
                        next()
                    })
                    .catch(() => {
                        store.dispatch('LogOut').then(res => {
                            if (res) {
                                next({ path: '/login' })
                            } else {
                                store.dispatch('FedLogOut').then(() => {
                                    next({ path: '/login' })
                                })
                            }
                        })
                    })
            } else {
                next()
            }
        }
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            const redirect = encodeURIComponent(to.fullPath) // 编码 URI，保证参数跳转回去后，可以继续带上
            next(`/login?redirect=${redirect}`) // 否则全部重定向到登录页
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done()
    serverLoadingInstance && serverLoadingInstance.close()
})
